package com.nondo.rdp.finance.endpoint.api.app;

import com.nondo.rdp.auth.common.UserUtils;
import com.nondo.rdp.auth.domain.User;
import com.nondo.rdp.auth.endpoint.model.ConvertCall;
import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.auth.endpoint.model.Query;
import com.nondo.rdp.auth.service.UserService;
import com.nondo.rdp.core.common.BeanUtils;
import com.nondo.rdp.core.common.CommUtil;
import com.nondo.rdp.core.common.ValidateUtil;
import com.nondo.rdp.core.domain.base.BaseEntity;
import com.nondo.rdp.core.model.View;
import com.nondo.rdp.finance.domain.UserFollow;
import com.nondo.rdp.finance.domain.analysis.*;
import com.nondo.rdp.finance.model.analysis.*;
import com.nondo.rdp.finance.service.UserFollowService;
import com.nondo.rdp.finance.service.analysis.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@RestController("apiAppAnalysis")
@RequestMapping("/api/app/analysis")
public class AnalysisEndpoint {
    @Autowired
    AnalysisService analysisService;

    @Autowired
    AnalysisCommentService analysisCommentService;

    @Autowired
    AnalysisUpService analysisUpService;

    @Autowired
    AnalysisCommentUpService analysisCommentUpService;

    @Autowired
    AnalysisComplainService analysisComplainService;

    @Autowired
    AnalysisCollectionService analysisCollectionService;

    @Autowired
    UserFollowService userFollowService;

    @Autowired
    UserService userService;

    @Autowired
    AnalysisReadService analysisReadService;

    @RequestMapping("/info/{id}")
    public View info(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) {
        View view = new View(20000, "获取数据成功");

        User user = UserUtils.checkUser();

        Analysis analysis = analysisService.findOne(id);

        if (analysis == null) {
            return View.ofError("不存在的分析");
        }

        //增加分析的阅读量
        analysis.setReadNum(analysis.getReadNum() + 1);
        this.analysisService.save(analysis);

        //处理返回值
        AnalysisBean analysisBean = new AnalysisBean();
        BeanUtils.copy(analysis, analysisBean);

        //处理返回图片
        analysisBean.setMainImg(CommUtil.getFileUrl(analysisBean.getMainImg()));

        //处理返回日期
        analysisBean.setCreatedDateString(CommUtil.dateFormat(analysisBean.getCreateDate(), "yyyy-MM-dd"));

        Map extra = new HashMap();

        extra.put("isCollection", 0);
        extra.put("isFollow", 0);
        extra.put("isUp", 0);
        if (user.getId() != null) {
            //该用户是否已经收藏
            AnalysisCollection analysisCollection = this.analysisCollectionService.findByAnalysisAndUser(analysis, user);
            if (analysisCollection != null) {
                extra.put("isCollection", 1);
            }

            //该用户是否已经关注
            User author = this.userService.findOne(analysis.getUser().getId());
            UserFollow userFollow = this.userFollowService.findByFollowerAndUser(author, user);
            if (userFollow != null) {
                extra.put("isFollow", 1);
            }

            //该用户是否已经点赞
            AnalysisUp analysisUp = this.analysisUpService.findByAnalysisAndUser(analysis, user);
            if (analysisUp != null) {
                extra.put("isUp", 1);
            }

            //设置为用户已读
            AnalysisRead analysisRead = this.analysisReadService.findByAidAndUid(analysisBean.getId(), user.getId());
            if (analysisRead == null) {
                analysisRead = new AnalysisRead();
                analysisRead.setAid(analysisBean.getId());
                analysisRead.setUid(user.getId());
                this.analysisReadService.save(analysisRead);
            }
        }

        analysisBean.setExtra(extra);

        //处理评论
        List newComment = new ArrayList();
        for (AnalysisComment commentItem : analysis.getComment()) {
            AnalysisCommentBean analysisCommentBean = new AnalysisCommentBean();
            BeanUtils.copy(commentItem, analysisCommentBean);

            //判断当前用户是否点赞
            analysisCommentBean.setIsUp(0);
            if (user.getId() != null) {
                AnalysisCommentUp analysisCommentUp = this.analysisCommentUpService.findByAnalysisCommentAndUser(commentItem, user);
                if (analysisCommentUp != null && analysisCommentUp.getDelFlag().equals("0")) {
                    analysisCommentBean.setIsUp(1);
                }
            }

            //处理评论时间和回复时间

            newComment.add(analysisCommentBean);
        }
        analysisBean.setComment(newComment);

        view.setData(analysisBean);

        return view;
    }

    @RequestMapping("/list")
    public View<Page<AnalysisBean>> list(HttpServletRequest request, HttpServletResponse response, @RequestBody Query<Analysis> query) {
        View<Page<AnalysisBean>> view = new View(20000, "获取列表成功");

        User user = UserUtils.checkUser();

        Analysis analysis = query.getData();

        Page<Analysis> page = analysisService.findAll(new Page<Analysis>(query.getPage(), query.getSize()), analysis);

        Page<AnalysisBean> resultPage = page.convertPage(new ConvertCall<Analysis, Page<AnalysisBean>>() {
            @Override
            public Page<AnalysisBean> execute(Page<Analysis> srcPage) {
                Page<AnalysisBean> analysisBeanPage = new Page<AnalysisBean>(srcPage.getPageNumber(), srcPage.getPageSize(), srcPage.getTotalPages(), srcPage.getTotalElements());
                //处理数据
                List<AnalysisBean> list = new ArrayList<AnalysisBean>();
                for (Object item : srcPage.getContent()) {
                    AnalysisBean analysisBean = new AnalysisBean();
                    BeanUtils.copy(item, analysisBean);

                    if (analysis.getType() == 4) {
                        //处理返回日期
                        analysisBean.setCreatedDateString(CommUtil.dateFormatTodayAndBefore(analysisBean.getCreateDate()));
                    } else {
                        //处理返回日期
                        analysisBean.setCreatedDateString(CommUtil.dateFormat(analysisBean.getCreateDate(), "MM.dd"));
                    }

                    //处理是否已读未读
                    analysisBean.setIsRead(0);
                    if (user.getId() != null) {
                        AnalysisRead analysisRead = analysisReadService.findByAidAndUid(analysisBean.getId(), user.getId());
                        if (analysisRead != null) {
                            analysisBean.setIsRead(1);
                        }
                    }


                    //处理图片
                    analysisBean.setMainImg(CommUtil.getFileUrl(analysisBean.getMainImg()));
                    list.add(analysisBean);
                }
                analysisBeanPage.setContent(list);

                return analysisBeanPage;
            }
        });

        view.setData(resultPage);

        return view;
    }

    @RequestMapping(value = "/add", produces = "application/json;charset=UTF-8")
    public View<AnalysisBean> add(HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody AnalysisBean analysisBean, BindingResult result) {
        View<AnalysisBean> view = new View<>(20000, "添加成功");

        User user = UserUtils.getUser(request, response);

        if (result.hasErrors()) {
            view.setCode(40000);
            view.setMessage(ValidateUtil.first(result.getAllErrors()));
        } else {
            Analysis analysis = new Analysis();
            BeanUtils.copy(analysisBean, analysis);

            //用户只能发布个股分析
//            analysis.setType(Analysis.TYPE_GENERAL_USER);
            analysis.setUser(user);
            this.analysisService.update(analysis);
            view.setData(analysisBean);
        }
        return view;
    }

    @RequestMapping("/update")
    public View update(HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody AnalysisBean analysisBean, BindingResult result) {
        if (result.hasErrors()) {
            return View.ofError(ValidateUtil.first(result.getAllErrors()));
        } else {
            User user = UserUtils.getUser(request, response);
            Analysis analysis = this.analysisService.findOne(analysisBean.getId());

            //验证是不是本人进行的更新
            if (user.getId().equals(analysis.getUser().getId())) {
                return View.ofError("对不起，你没有权限进行操作");
            }

            BeanUtils.copy(analysisBean, analysis);
            this.analysisService.update(analysis);
        }

        return View.ofOk("更新成功");
    }

    @RequestMapping("/delete/{id}")
    public View delete(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) {
        User user = UserUtils.getUser(request, response);
        Analysis analysis = this.analysisService.findOne(id);

        //验证是不是本人进行的更新
        if (user.getId().equals(analysis.getUser().getId())) {
            return View.ofError("对不起，你没有权限进行操作");
        }

        this.analysisService.delete(id);

        return View.ofOk("删除成功");
    }

    @RequestMapping("/comment/{id}")
    public View comment(@PathVariable("id") long id, HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody AnalysisCommentBean analysisCommentBean, BindingResult result) {
        User user = UserUtils.getUser(request, response);

        if (result.hasErrors()) {
            return View.ofError(ValidateUtil.first(result.getAllErrors()));
        } else {
            //获取分析
            Analysis analysis = this.analysisService.findOne(id);

            //增加分析评论
            AnalysisComment analysisComment = new AnalysisComment();
            BeanUtils.copy(analysisCommentBean, analysisComment);

            analysisComment.setAnalysis(analysis);
            analysisComment.setUser(user);
            this.analysisCommentService.save(analysisComment);

            //增加总评论数量
            analysis.setCommentNum(analysis.getCommentNum() + 1);
            this.analysisService.save(analysis);
        }

        return View.ofOk("回复成功");
    }

    @RequestMapping("/comment/delete/{id}")
    public View commentDelete(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) {
        User user = UserUtils.getUser(request, response);
        AnalysisComment analysisComment = this.analysisCommentService.findOne(id);

        if (!user.getId().equals(analysisComment.getUser().getId())) {
            return View.ofError("对不起，你没有权限进行操作");
        }

        this.analysisCommentService.delete(id);

        //减去分析评论数量
        Analysis analysis = this.analysisService.findOne(analysisComment.getAnalysis().getId());
        if (analysisComment.getDelFlag().equals(BaseEntity.DEL_FLAG_NORMAL) && analysis.getCommentNum() > 1) {
            analysis.setComplaintNum(analysis.getCommentNum() - 1);
            this.analysisService.save(analysis);
        }

        return View.ofOk("删除成功");
    }

    @RequestMapping("/up")
    public View<AnalysisUpBean> up(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) {
        View<AnalysisUpBean> view = new View<>(20000, "点赞成功");

        Analysis analysis = this.analysisService.findOne(id);
        User user = UserUtils.getUser(request, response);

        //检查是否已经存在点赞数据了
        AnalysisUp isAnalysisUp = this.analysisUpService.findByAnalysisAndUser(analysis, user);
        if (isAnalysisUp == null) {
            AnalysisUp analysisUp = new AnalysisUp();

            analysisUp.setAnalysis(analysis);
            analysisUp.setUser(user);
            this.analysisUpService.save(analysisUp);
        } else if (isAnalysisUp.getDelFlag() == BaseEntity.DEL_FLAG_NORMAL) {
            view.setMessage("已经点过赞了");
            return view;
        } else {
            isAnalysisUp.setDelFlag(BaseEntity.DEL_FLAG_NORMAL);
            this.analysisUpService.save(isAnalysisUp);
        }

        //增加分析的点赞数量
        analysis.setUpNum(analysis.getUpNum() + 1);
        this.analysisService.save(analysis);

        return view;
    }

    @RequestMapping("/up/cancel/{id}")
    public View upCancel(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) {
        View view = new View(20000, "取消点赞成功");

        Analysis analysis = this.analysisService.findOne(id);
        User user = UserUtils.getUser(request, response);

        AnalysisUp analysisUp = this.analysisUpService.findByAnalysisAndUser(analysis, user);
        if (analysisUp != null && BaseEntity.DEL_FLAG_NORMAL.equals(analysisUp.getDelFlag())) {
            this.analysisUpService.delete(analysisUp.getId());

            //减少分析的点赞数量
            analysis.setUpNum(analysis.getUpNum() - 1);
            this.analysisService.save(analysis);
        }

        return view;
    }


    @RequestMapping("/comment/up/{id}")
    public View<AnalysisCommentUpBean> commentUp(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) {
        View<AnalysisCommentUpBean> view = new View<>(20000, "评论点赞成功");

        AnalysisComment analysisComment = this.analysisCommentService.findOne(id);
        User user = UserUtils.getUser(request, response);

        //检查是否已经存在点赞数据了
        AnalysisCommentUp isAnalysisCommentUp = this.analysisCommentUpService.findByAnalysisCommentAndUser(analysisComment, user);
        if (isAnalysisCommentUp == null) {
            AnalysisCommentUp AnalysisCommentUp = new AnalysisCommentUp();

            AnalysisCommentUp.setAnalysisComment(analysisComment);
            AnalysisCommentUp.setUser(user);
            this.analysisCommentUpService.save(AnalysisCommentUp);
        } else if (isAnalysisCommentUp.getDelFlag().equals(BaseEntity.DEL_FLAG_DELETE)) {
            isAnalysisCommentUp.setDelFlag(BaseEntity.DEL_FLAG_NORMAL);
            this.analysisCommentUpService.save(isAnalysisCommentUp);
        } else {
            return view;
        }

        //增加点赞数量
        analysisComment.setUpNum(analysisComment.getUpNum() + 1);
        this.analysisCommentService.save(analysisComment);

        return view;
    }

    @RequestMapping("/comment/up/cancel/{id}")
    public View commentUpCancel(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) {
        View view = new View(20000, "取消评论点赞成功");

        User user = UserUtils.getUser(request, response);

        AnalysisComment analysisComment = this.analysisCommentService.findOne(id);
        AnalysisCommentUp isAnalysisCommentUp = this.analysisCommentUpService.findByAnalysisCommentAndUser(analysisComment, user);
        if (isAnalysisCommentUp != null && isAnalysisCommentUp.getDelFlag().equals(BaseEntity.DEL_FLAG_NORMAL)) {
            //取消点赞
            isAnalysisCommentUp.setDelFlag(BaseEntity.DEL_FLAG_DELETE);
            this.analysisCommentUpService.save(isAnalysisCommentUp);
            //减少点赞数量
            analysisComment.setUpNum(analysisComment.getUpNum() - 1);
            this.analysisCommentService.save(analysisComment);
        }

        return view;
    }

    @RequestMapping("/author/comment")
    public View<AnalysisBean> anthorComment(HttpServletRequest request, HttpServletResponse response, @RequestBody AnalysisCommentBean analysisCommentBean) {
        AnalysisComment analysisComment = this.analysisCommentService.findOne(analysisCommentBean.getId());
        User user = UserUtils.getUser(request, response);

        //判断回复者是不是作者
        if (!user.getId().equals(analysisComment.getUser().getId())) {
            return View.ofError("非作者本人不能进行回复");
        }

        analysisComment.setUser(user);
        analysisComment.setComent(analysisCommentBean.getComent());
        analysisComment.setAuthorComentDate(new Date());
        this.analysisCommentService.save(analysisComment);

        return View.ofOk("回复成功");
    }

    @RequestMapping("/complain/{id}")
    public View<AnalysisComplainBean> complain(HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody AnalysisComplainBean analysisComplainBean, BindingResult result) {
        View<AnalysisComplainBean> view = new View<>(20000, "投诉成功");

        Analysis analysis = this.analysisService.findOne(analysisComplainBean.getAnalysis().getId());

        User user = UserUtils.getUser(request, response);

        //检查是否已经存在投诉数据了
        AnalysisComplain isAnalysisComplain = this.analysisComplainService.findByAnalysisAndUser(analysis, user);
        if (isAnalysisComplain == null) {
            if (result.hasErrors()) {
                view.setCode(40000);
                view.setMessage(ValidateUtil.first(result.getAllErrors()));
            } else {
                AnalysisComplain AnalysisComplain = new AnalysisComplain();
                BeanUtils.copy(analysisComplainBean, AnalysisComplain);

                AnalysisComplain.setAnalysis(analysis);
                AnalysisComplain.setUser(user);
                this.analysisComplainService.save(AnalysisComplain);

                //增加分析的投诉数量
                analysis.setComplaintNum(analysis.getComplaintNum() + 1);
                this.analysisService.save(analysis);
            }
        } else {
            view.setMessage("感谢你的投诉，我们会进行审核并处理违规行为");
        }

        return view;
    }

    @RequestMapping("/collection/{id}")
    public View<AnalysisCollectionBean> collection(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) {
        Analysis analysis = this.analysisService.findOne(id);
        User user = UserUtils.getUser(request, response);

        //检查是否已经存在点赞数据了
        AnalysisCollection isAnalysisCollection = this.analysisCollectionService.findByAnalysisAndUser(analysis, user);
        if (isAnalysisCollection == null) {
            AnalysisCollection analysisCollection = new AnalysisCollection();

            analysisCollection.setAnalysis(analysis);
            analysisCollection.setUser(user);
            //设置标题和图片
            analysisCollection.setTitle(analysis.getTitle());
            analysisCollection.setImage(analysis.getMainImg());

            this.analysisCollectionService.save(analysisCollection);
        } else {
            isAnalysisCollection.setDelFlag(BaseEntity.DEL_FLAG_NORMAL);
            this.analysisCollectionService.save(isAnalysisCollection);
        }

        return View.ofOk("收藏成功");
    }

    @RequestMapping("/collection/cancel/{id}")
    public View collectionCancel(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) {
        View view = new View(20000, "取消收藏成功");

        this.analysisCollectionService.delete(id);

        return view;
    }

    @RequestMapping("/follow/{id}")
    public View follow(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) {
        User follower = this.userService.findOne(id);
        User user = UserUtils.getUser(request, response);

        //检查是否已经存在点赞数据了
        UserFollow isUserFollow = this.userFollowService.findByFollowerAndUser(follower, user);
        if (isUserFollow == null) {
            UserFollow userFollow = new UserFollow();
            userFollow.setFollower(follower);
            userFollow.setUser(user);
            userFollow.setStatus(UserFollow.STATUS_FOLLOW);
            this.userFollowService.save(userFollow);
        } else {
            isUserFollow.setStatus(UserFollow.STATUS_FOLLOW);
            this.userFollowService.save(isUserFollow);
        }

        return View.ofOk("关注成功");
    }

    @RequestMapping("/follow/cancel/{id}")
    public View followCancel(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) {
        User follower = this.userService.findOne(id);
        User user = UserUtils.getUser(request, response);

        UserFollow userFollow = this.userFollowService.findByFollowerAndUser(follower, user);
        userFollow.setStatus(UserFollow.STATUS_CANCEL);
        this.userFollowService.save(userFollow);

        return View.ofOk("取消关注成功");
    }
}